<template>
  <div>
    <Col :lg="24" :md="16">
    <Card class="warp-card" dis-hover>
      <Row justify="space-between" type="flex">
        <Col>
          <Input
            placeholder="部门名称"
            style="width: 200px;"
            v-model="searchForm.departmentName"
          />
          <Button
            @click="searchData" icon="md-search"
            style="margin-left: 20px;"
            type="primary"
            v-privilege="'search-department'"
          >查询
          </Button>
          <Button
            @click="clearSearch"
            style="margin-left: 20px;"
            icon="md-refresh"
            type="default"
            v-privilege="'search-department'"
          >重置
          </Button>
        </Col>
        <Col>
          <Button
            @click="isShowAddModal=true"
            icon="md-add"
            type="primary"
            v-privilege="'add-department'"
          >新建
          </Button>
        </Col>
      </Row>
      <!-- Form 搜索按钮区 end -->
      <Row style="padding-top:10px; ">
        <Table :columns="columns" :data="data" :loading="isShowTablesLoading" ref="tablesMain"></Table>
      </Row>
      <Row class="page" justify="end" style="position: relative;margin-top: 10px;" type="flex">
        <Page
          :current="searchForm.pageNum"
          :page-size="searchForm.pageSize"
          :total="totalPage"
          @on-change="changePage"
          show-total
          show-elevator
        ></Page>
      </Row>
    </Card>
    <!-- Card 内容区 end -->
    <Modal
      :loading="isShowUpdateLoading"
      :closable="false"
      title="编辑部门"
      width="740"
      v-model="isShowEditModal"
    >
      <Form :label-width="80" :model="updateItem" :rules="updateValidate" ref="updateRef">
        <FormItem class="select-class" label="机构" prop="orgId">
            <Select class="form-width" v-model="updateItem.orgId" @on-select='selectOrg'>
              <Option
                :key="item.id"
                :value="item.id"
                v-for="item in orgList"
              >{{ item.orgName }}</Option>
            </Select>
        </FormItem>
        <FormItem class="select-class" label="上级部门" prop="parentId">
          <Treeselect
            placeholder="请选择上级部门"
            v-model="updateItem.parentId"
            :options="treeNodeData"
            :load-options="loadOptions"
            loadingText="正在加载"
            noChildrenText="无子部门"
            retryText="重试?"
            retryTitle="点击重试"
            zIndex="99999"
            @select="selectNode">
            <div slot="option-label" slot-scope="{ node }" style="white-space: nowrap; font-size: 14px">
                   {{ node.raw.id}} ({{ node.raw.label}})
                </div>
                <div slot="value-label" slot-scope="{ node }">{{ node.raw.id}} ({{ node.raw.label}})</div>
          </Treeselect>
        </FormItem>
        <FormItem label="部门编号" prop="departmentCode">
          <Input :maxlength="30" placeholder="请输入部门编号(必填)" v-model="updateItem.departmentCode"></Input>
        </FormItem>
        <FormItem label="部门名称" prop="departmentName">
          <Input placeholder="请输入部门名称(必填)" v-model="updateItem.departmentName"></Input>
        </FormItem>
        <FormItem label="责任人" prop="managerCode">
          <Select
                placeholder="请输入责任人"
                v-model="updateItem.managerCode"
                filterable
                :remote-method="getUserListByName"
                :default-label="updateItem.managerName"
                :loading="loadingManager"
                ref="managerSelect"
                >
                <Option v-for="(user, index) in managerUserList" :value="user.username" :key="index">
                  {{user.actualName}}
                </Option>
            </Select>
        </FormItem>
        <FormItem label="部门描述" prop="remark">
          <Input
            :maxlength="maxlength"
            :autosize="{minRows: 5, maxRows: 8 }"
            placeholder="请输入部门描述"
            @input="descInput"
            type="textarea"
            v-model="updateItem.remark "
          ></Input>
          <span class="text">{{ remnant }}/{{maxlength}}</span>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          @click="cancelUpdateData"
        >取消</Button>
        <Button
          type="primary"
          @click="validateAndUpdateDepartment"
        >确定</Button>
      </div>
    </Modal>
    <Modal
      :loading="isShowSaveLoading"
      title="新建部门"
      :closable="false"
      width="740"
      v-model="isShowAddModal"
    >
      <Form :label-width="80" :model="saveItem" :rules="saveValidate" ref="saveRef">
        <FormItem class="select-class" label="机构" prop="orgId">
            <Select class="form-width" v-model="saveItem.orgId" @on-select='selectOrg'>
              <Option
                :key="item.id"
                :value="item.id"
                v-for="item in orgList"
              >{{ item.orgName }}</Option>
            </Select>
        </FormItem>
        <FormItem class="select-class" label="上级部门" prop="parentId">
          <Treeselect
            placeholder="请选择上级部门"
            v-model="saveItem.parentId"
            :options="treeNodeData"
            :load-options="loadOptions"
            loadingText="正在加载"
            noChildrenText="无子部门"
            retryText="重试?"
            retryTitle="点击重试"
            :appendToBody="true"
            :auto-load-root-options="false"
            zIndex="99999"
            @select="selectNode">
            <div slot="option-label" slot-scope="{ node }" style="white-space: nowrap; font-size: 14px">
                   {{ node.raw.id}} ({{ node.raw.label}})
                </div>
            <div slot="value-label" slot-scope="{ node }">{{ node.raw.id}} ({{ node.raw.label}})</div>
          </Treeselect>
        </FormItem>
        <FormItem label="部门编号" prop="departmentCode">
          <Input :maxlength="30" placeholder="请输入部门编号(必填)" v-model="saveItem.departmentCode"></Input>
        </FormItem>
        <FormItem label="部门名称" prop="departmentName">
          <Input :maxlength="30" placeholder="请输入部门名称(必填)" v-model="saveItem.departmentName"></Input>
        </FormItem>
        <FormItem label="责任人" prop="managerName">
          <Select
                placeholder="请输入责任人"
                v-model="saveItem.managerCode"
                filterable
                :remote-method="getUserListByName"
                :loading="loadingManager">
                <Option v-for="(user, index) in managerUserList" :value="user.username" :key="index">
                  {{user.actualName}}
                </Option>
            </Select>
        </FormItem>
        <FormItem label="部门描述" prop="remark">
          <Input
            :autosize="{minRows: 5, maxRows: 8 }"
            :maxlength="maxlength"
            @input="descInput"
            placeholder="请输入部门描述"
            type="textarea"
            v-model="saveItem.remark "
          ></Input>
           <span class="text">{{ remnant }}/{{maxlength}}</span>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          @click="cancelSaveData"
        >取消</Button>
        <Button
          type="primary"
          @click="validateAndAddDepartment"
        >确定</Button>
      </div>
    </Modal>
    <!-- Modal 添加部门弹窗 end -->
    </Col>
  </div>
</template>

<script>
import { departmentApi } from '@/api/department';
import { userApi } from '@/api/sys-user';
import { validateTextLength } from '@/lib/util';
import { orgApi } from '@/api/org';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { LOAD_ROOT_OPTIONS } from '@riophae/vue-treeselect';
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect';

let firstLoadDepartment = false

export default {
  name: 'DepartmentManage',
  components: {
    Treeselect
  },
  props: {},
  data() {
    return {
      isShowPage: true,
      searchValue: '',
      remnant: 200,
      maxlength:200,
      orgList:[],
      isShowEditModal: false,
      isShowAddModal: false,
      // table是否Loading
      isShowTablesLoading: true,
      isShowSaveLoading: true,
      isShowUpdateLoading: true,
      totalPage: 0,
      treeNodeData: null,
      parentDepartmentId: null,
      loadingManager: false,
      managerUserList: [{
        managerCode: '',
        managerName: ''
      }],
      selectedNode: null,
      // 更新的数据
      updateItem: {
        id: '',
        orgId:'',
        parentId:'',
        departmentName: '',
        managerName:'',
        remark: ''
      },
      // 添加保存的数据
      saveItem: {
        orgId:'',
        parentId:'',
        departmentName: '',
        managerName:'',
        remark: ''
      },
      saveItemInt: {},
      // table表头
      columns: [
        {
          title: '机构名称',
          key: 'orgName',
          width: 200
        },
        {
          title: '部门名称',
          key: 'departmentName',
          width: 160
        },
        {
          title: '上级部门名称',
          key: 'parentDepartmentNames',
          width: 300,
          ellipsis: true,
          tooltip: true
        },
        {
          title: '描述',
          key: 'remark',
          width: 180
        },
         {
          title: '责任人',
          key: 'managerName',
          width: 80
        },
        {
          key: 'isDisabled',
          width: 80,
          title: '状态',
          align: 'left',
          render: (h, params) => {
            let disabled = params.row.isDisabled;
            return h('i-switch', {
                props: {
                  size: "large",
                  value: !disabled
                },
                on: {
                  'on-change': (value) => {
                    params.row.status = value;
                    const th = this;
                    this.updateDepartmentStatus(th,params);
                  }
                }
              },
              [h('span', {
                slot: "open",
                domProps: {
                  innerHTML: '启用'
                }
              }),
                h('span', {
                  slot: "close",
                  domProps: {
                    innerHTML: '禁用'
                  }
                }),
              ]
            )
          }
        },
        {
          key: 'createTime',
          width: 160,
          title: '创建时间',
          align: 'left',
          width: 130
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          className: 'action-hide',
          render: (h, params) => {
            return this.$tableAction(h, [
              {
                title: '编辑',
                directives: [
                  {
                    name: 'privilege',
                    value: 'update-department'
                  }
                ],
                action: () => {
                  this.getDepartmentDetail(params.row.id)
                  this.isShowEditModal = true
                }
              },
              {
                title: '删除',
                directives: [
                  {
                    name: 'privilege',
                    value: 'delete-department'
                  }
                ],
                action: () => {
                  this.$Modal.confirm({
                    title: '友情提醒',
                    content: '确定要删除吗？',
                    onOk: () => {
                      this.deleteDepartmentById(params.row.id);
                    }
                  });
                }
              }
            ]);
          }
        }
      ],
      // table数据
      data: [],
      updateValidate: {
        departmentName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        orgId: [{ required: true, message: '请选择组织机构', trigger: 'blur',type:'number' }]
      },
      saveValidate: {
        departmentCode: [
          { required: true, message: '请输入部门编号', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        orgId: [{ required: true, message: '请选择组织机构', trigger: 'blur',type:'number' }]
      },
      searchForm: {
        departmentName: '',
        pageNum: 1,
        pageSize: 10,
        searchCount: true,
        sort: false
      },
      searchFormInt: {},
      isShowdeleteLoading: false
    };
  },
  computed: {},
  watch: {
    isShowAddModal(val) {
      if (val) {
        this.remnant = 0
        this.selectOrg();
      }
    },
    isShowEditModal(val) {
      if (val) {
        this.selectOrg();
      }
    }
  },
  filters: {},
  created() {},
  mounted() {
    Object.assign(this.searchFormInt, this.searchForm);
    Object.assign(this.saveItemInt, this.saveItem);
    this.getDepartmentListPage();
    firstLoadDepartment = false;
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    // 分页查询所有岗位
    async getDepartmentListPage() {
      try {
        this.isShowTablesLoading = true;
        this.isShowPage = true;
        let result = await departmentApi.getDepartmentListPage(this.searchForm);
        this.isShowTablesLoading = false;
        let datas = result.data;
        this.data = datas.list;
        this.totalPage = datas.total;
      } catch (e) {
        this.isShowTablesLoading = false;
        console.error(e);
      }
    },
    async getDepartmentTree(parentId) {
      let res = await departmentApi.getDepartmentTreeByParent(parentId);
      if (res.code === 1) {
        this.treeNodeData = res.data;
      }
    },
    // 根据用户姓名查询
    async getUserListByName(queryName) {
      if (queryName != null && queryName != '' && queryName.trim() != '') {
        let res = await userApi.getListUserByName(queryName);
        if (res.code === 1) {
          this.managerUserList = res.data;
        }
      }
    },
     descInput() {
      let remark = this.updateItem.id?this.updateItem.remark:this.saveItem.remark;
      let txtVal = validateTextLength(remark);
      this.remnant = this.maxlength - txtVal;
    },
     async selectOrg(){
      let result = await orgApi.getOrgList();
      this.orgList = result.data;
    },
    async getDepartmentDetail(departmentId){
      let res = await departmentApi.getDepartmentById(departmentId);
      if (res.code === 1) {
        const data = res.data
        this.updateItem = { ...data }
        // this.$refs.managerSelect.query = data.managerName
        // this.getUserListByName(data.managerName);
        this.descInput()
      }
    },
    // 禁用/启用部门
    async updateDepartmentStatus(h,params) {
      try {
        this.isShowTablesLoading = true;
        let userId = params.row.id;
        let status = params.row.status;
        let result = await departmentApi.updateStatus(userId, status?0:1);
        this.isShowTablesLoading = false;
        if (!status) {
          this.$Message.success('禁用成功');
        } else {
          this.$Message.success('启用成功');
        }
        this.getUserList();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    },
    // 页码改变
    changePage(pageNum) {
      this.searchForm.pageNum = pageNum;
      this.getDepartmentListPage();
    },
    // 改变每页显示数据条数
    changePageSize(pageSize) {
      this.searchForm.pageNum = 1;
      this.searchForm.pageSize = pageSize;
      this.getDepartmentListPage();
    },
    // 检验参数后 更新部门
    validateAndUpdateDepartment() {
      this.$refs['updateRef'].validate(valid => {
        this.isShowUpdateLoading = true;
        if (valid) {
          this.updateDepartment();
        } else {
          this.isShowUpdateLoading = false;
          this.$nextTick(() => {
            this.isShowUpdateLoading = true;
          });
        }
      });
    },
    // 更新部门
    async updateDepartment() {
      try {
        let result = await departmentApi.updateDepartment(this.updateItem);
        this.$Message.success('修改成功');
        this.$emit('updateSuccess');
        await this.getDepartmentListPage();
        this.cancelUpdateData();
      } catch (e) {
        this.isShowUpdateLoading = false;
        this.$nextTick(() => {
          this.isShowUpdateLoading = true;
        });
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowUpdateLoading = false;
      }
    },
    // 清除编辑模态框数据
    cancelUpdateData() {
      this.updateItem = {};
      // 清空form规则检查
      this.$refs['updateRef'].resetFields();
      this.isShowEditModal = false;
    },
    // 搜索
    searchData() {
      this.pageNum = 1;
      this.getDepartmentListPage();
    },
    // 重置
    clearSearch() {
      Object.assign(this.searchForm, this.searchFormInt);
      this.getDepartmentListPage();
    },
    // 新增部门
    validateAndAddDepartment() {
      try {
        this.$refs['saveRef'].validate(valid => {
          this.isShowSaveLoading = true;
          if (valid) {
            this.addDepartment();
          } else {
            this.isShowSaveLoading = false;
            this.$nextTick(() => {
              this.isShowSaveLoading = true;
            });
          }
        });
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      }
    },
    // 新增部门 - 异步
    async addDepartment() {
      try {
        let result = await departmentApi.addDepartment(this.saveItem);
        if (result.code === 1) {
          if (this.selectedNode) {
            if (!this.selectedNode.children)
              this.selectedNode.children = [];
            this.selectedNode.children.push({
              id: result.data,
              label: this.saveItem.departmentName
            })
          }
          this.$Message.success('添加成功');
          this.$emit('addSuccess');
          this.isShowSaveLoading = true;
        }
        await this.getDepartmentListPage();
        this.cancelSaveData();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      }
    },
    // 清除添加模态框数据
    cancelSaveData() {
      Object.assign(this.saveItem, this.saveItemInt);
      // 清空form规则检查
      this.$refs['saveRef'].resetFields();
      this.isShowAddModal = false;
    },
    // 根据ID删除部门
    async deleteDepartmentById(id) {
      try {
        this.isShowdeleteLoading = true;
        let result = await departmentApi.deleteDepartment(id);
        this.isShowdeleteLoading = false;
        this.$Message.success('删除成功');
        await this.getDepartmentListPage();
        this.cancelSaveData();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowdeleteLoading = false;
      }
    },
    async loadOptions({ action, parentNode, callback }) {
      if (action === LOAD_ROOT_OPTIONS) {
        if (!firstLoadDepartment) {
          let res = await departmentApi.getDepartmentTreeByParent(0);
          if (res.code === 1) {
            this.treeNodeData = res.data;
            firstLoadDepartment = true;
          }
        }
      } else if (action === LOAD_CHILDREN_OPTIONS) {
        if (parentNode.id) {
          let res = await departmentApi.getDepartmentTreeByParent(parentNode.id);
            if (res.code === 1) {
              parentNode.children = res.data;
              callback();
            }
        } else {
          callback(new Error('未选中元素'))
        }
      }
    },
    selectNode(node, instanceId) {
      this.selectedNode = node;
    }
  }
};
</script>
<style lang="less" scoped>
.text{
    position: absolute;
    right: 10px;
    bottom: -5px;
}
</style>
